class UsersController < ApplicationController
  
  before_filter :must_be_admin, :except => [:index,:current, :show,:edit_current,:update_current]

  before_filter :must_be_colleague, :only => [:edit,:update,:edit_current,:update_current,:reset_password, :lock, :active, :disable]
  
  def index
    params[:group_id] ||= '%'
    params[:status] ||= 'active'
    params[:key_words] ||= ''
    if params[:group_id] != '%' 
      @group = Group.find(params[:group_id])
    end
    @users = (@group.present? ? @group.users : current_user.enterprise.users).where(:status => params[:status]).where('full_name like ? or mobile like ? or email like ? ',"%#{params[:key_words]}%","%#{params[:key_words]}%","%#{params[:key_words]}%")
  end

  def new
    @user = User.new
  end

  def edit
    @user = User.find(params[:id])
  end

  def create
    @user = User.new params[:user]
    @user.enterprise_id = current_user.enterprise_id
    @user.reset_password
    if @user.save
      flash[:success] = "• 『#{@user.full_name}』的基本资料保存成功!"
      redirect_to :action => :index, :group_id => params[:group_id]
    else
      render :new 
    end
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      flash[:success] = "• 『#{@user.full_name}』的基本资料更新成功!"
      redirect_to :action => :index, :group_id => params[:group_id]
    else
      render :edit 
    end
  end
  
  def lock
    @user = User.find(params[:id])
    @user.locked!
    flash[:success] = "• 『#{@user.full_name}』已被锁定,Ta将无法使用系统了:_("
    redirect_to request.referer
  end

  def disable
    @user = User.find(params[:id])
    @user.disabled!
    flash[:success] = "• 『#{@user.full_name}』已被停用,Ta将无法使用系统了:_("
    redirect_to request.referer
  end  
  
  def active
    @user = User.find(params[:id])
    @user.active!
    flash[:success] = "• 『#{@user.full_name}』已被激活,赶紧通知Ta可以使用系统了:)"
    redirect_to request.referer
  end

  def reset_password
    @user = User.find(params[:id])
    @user.reset_password!
    flash[:success] = "• 『#{@user.full_name}』密码已经重置，请通知Ta尽快修改新密码:)"
    redirect_to request.referer
  end

  def current
    @user = current_user
  end

  def show
    @user = User.current_enterprise.find(params[:id])
  end

  def edit_current
    @user = current_user
  end

  def update_current
    @user = current_user
    if @user.update_attributes(params[:user])
      flash[:success] = "• 我的基本资料更新成功!"
      redirect_to :action => :current
    else
      render :edit_current
    end
  end

  def sort
    params[:user].each_with_object([]) do |user_id,users|
      users << User.find(user_id)
    end.each_with_index do |user,index|
      user.position!( index + 1)
    end
    render :text => 'success'
  end  
  
end
